package master;

import javax.swing.GroupLayout;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.BoxLayout;
import javax.swing.Box;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
import javax.swing.JFrame;

import common.JobObject;
import common.JobsPackage;
import common.WorkerObject;

import java.beans.*; //Property change stuff
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.awt.*;
import java.awt.event.*;

/*
 * DialogDemo.java requires these files:
 *   CustomDialog.java
 *   images/middle.gif
 */
public class ServerInfoGUI extends JPanel implements Runnable {
    JLabel label;
    static JFrame frame;
	static JFrame frame2;
    String simpleDialogDesc = "Some simple message dialogs";
    String iconDesc = "A JOptionPane has its choice of icons";
    String moreDialogDesc = "Some more dialogs";
    static MasterService masterService;
    

    /** Creates the GUI shown inside the frame's content pane. */
    public ServerInfoGUI(JFrame frame, JFrame frame2, MasterService masterService) {
        super(new BorderLayout());
        this.frame = frame;
        this.frame2 = frame2;
        this.masterService = masterService;

        //Create the components.
        JPanel frequentPanel = createJobsPanel();
        JPanel featurePanel = createWorkersPanel();
        JPanel iconPanel = new JPanel();


        //Lay them out.
        Border padding = BorderFactory.createEmptyBorder(20,20,5,20);
        frequentPanel.setBorder(padding);
        featurePanel.setBorder(padding);
        iconPanel.setBorder(padding);

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Jobs", null,
                          frequentPanel); //tooltip text
        tabbedPane.addTab("Workers", null,
                          featurePanel); //tooltip text


        add(tabbedPane, BorderLayout.CENTER);
 
    }
    
    private JPanel createWorkersPanel() {
    	
    	final JScrollPane jScrollPane1 = new JScrollPane();
    	jScrollPane1.setName("jScrollPane1");
        JButton jButton1 = new JButton();
        //JButton jButton2 = new JButton();
        jButton1.setText("Refresh");
        //jButton2.setText("Get Result");
        final JTable jTable1 = new JTable();
        jTable1.setName("jTable1");
        jScrollPane1.setViewportView(jTable1);
        Iterator<Integer> iter = masterService.workerInfo.keySet().iterator();
        int numItems = masterService.workerInfo.keySet().size();
        Object[][] objects = new Object[numItems][4];
        int i = 0;
        while (iter.hasNext()) {
	        WorkerObject worker = masterService.workerInfo.get(iter.next());
        	Object[] line = new Object[4];
	            
	        // Assign the value to the line object.
	        line[0] = String.valueOf(worker.getWorkerID());
	        line[1] = String.valueOf(worker.getRegTime());
	        line[2] = String.valueOf(worker.getPrice());
	        line[3] = String.valueOf(worker.getStatus());
	        objects[i++] = line;

	    }

	    jTable1.setModel(new javax.swing.table.DefaultTableModel(objects, new String[] { "WORKER ID", "TIMESTAMP", "PRICE/SEC", "STATE"}));

        jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                 jTable1.setName("jTable1");
                 jScrollPane1.setViewportView(jTable1);
                 Iterator<Integer> iter = masterService.workerInfo.keySet().iterator();
                 int numItems = masterService.workerInfo.keySet().size();
                 Object[][] objects = new Object[numItems][4];
                 int i = 0;
                 while (iter.hasNext()) {
         	        WorkerObject worker = masterService.workerInfo.get(iter.next());
                 	Object[] line = new Object[4];
         	            
         	        // Assign the value to the line object.
         	        line[0] = String.valueOf(worker.getWorkerID());
         	        line[1] = String.valueOf(worker.getRegTime());
         	        line[2] = String.valueOf(worker.getPrice());
         	        line[3] = String.valueOf(worker.getStatus());
         	        objects[i++] = line;

         	    }

         	    jTable1.setModel(new javax.swing.table.DefaultTableModel(objects, new String[] { "WORKER ID", "TIMESTAMP", "PRICE/SEC", "STATE"}));
         	
            }
        });
        GroupLayout layout = new GroupLayout(frame2.getContentPane());
        frame2.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 656, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(274, 274, 274)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
        frame2.pack();
        JPanel pane = new JPanel(new BorderLayout());
        pane.add(frame2.getContentPane());
        //frame.setVisible(false);
        return pane;
    
    
    }

    
    private JPanel createJobsPanel() {
    	
    	final JScrollPane jScrollPane1 = new JScrollPane();
    	jScrollPane1.setName("jScrollPane1");
        JButton jButton1 = new JButton();
        //JButton jButton2 = new JButton();
        jButton1.setText("Refresh");
        //jButton2.setText("Get Result");
        
        
        
        ArrayList<String> clientIDs = new ArrayList<String>();
        ArrayList<Integer> jobIDs = new ArrayList<Integer>();
        final JTable jTable1 = new JTable();
 
        jTable1.setName("jTable1");
        jScrollPane1.setViewportView(jTable1);
        Iterator<String> iter = masterService.jobPackageInfo.keySet().iterator();
        int numItems = 0;
        while (iter.hasNext()) {
        	numItems += masterService.jobPackageInfo.get(iter.next()).getNumberOfJobs();
        }
        iter = masterService.jobPackageInfo.keySet().iterator();
        Object[][] objects = new Object[numItems][5];
        int acc = 0;
        while (iter.hasNext()) {
	        JobsPackage jp = masterService.jobPackageInfo.get(iter.next());
        	List<JobObject> list = jp.getJobs();
	        
	        for (int i = 0; i < list.size(); i++) {
	            // Create a line object, each line contains four elements.
	            Object[] line = new Object[5];
	            
	            // Assign the value to the line object.
	            line[0] = String.valueOf(list.get(i).getClientID());
	            line[1] = String.valueOf(list.get(i).getJobID());
	            line[2] = String.valueOf(list.get(i).getExecuteFileName());
	            line[3] = String.valueOf(list.get(i).getStatus());
	            // Create a button.
	            JButton killButton = new JButton("Kill Job");
	            line[4] = killButton;
	            
	            // Set the properties of the button.
	            killButton.setName(String.valueOf(list.get(i).getJobID()));
	            killButton.setText("Kill Job");
	            
	            // If this job hasn't finished,then disable the "Kill Job" button.
	            if ("COMPLETED".equals(list.get(i).getStatus())) {
	                killButton.setEnabled(false);
	            }
	            
	            objects[acc+ i] = line;
	            clientIDs.add(list.get(i).getClientID());
	            jobIDs.add(list.get(i).getJobID());
	        }
	        
	        acc += list.size();
	        
	        
	    }
	    jTable1.setModel(new javax.swing.table.DefaultTableModel(objects, new String[] { "CLIENT ID", "JOB ID", "JOB NAME", "STATE",
        "ACTION" }));
	    jTable1.getColumn("ACTION").setCellRenderer(new MyRender(clientIDs, jobIDs, masterService));
	    

	    jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
            	ArrayList<String> clientIDs = new ArrayList<String>();
                ArrayList<Integer> jobIDs = new ArrayList<Integer>();
                jTable1.setName("jTable1");
                jScrollPane1.setViewportView(jTable1);
                Iterator<String> iter = masterService.jobPackageInfo.keySet().iterator();
                int numItems = 0;
                while (iter.hasNext()) {
                	numItems += masterService.jobPackageInfo.get(iter.next()).getNumberOfJobs();
                }
                iter = masterService.jobPackageInfo.keySet().iterator();
                Object[][] objects = new Object[numItems][5];
                int acc = 0;
                while (iter.hasNext()) {
        	        JobsPackage jp = masterService.jobPackageInfo.get(iter.next());
                	List<JobObject> list = jp.getJobs();
        	        
        	        for (int i = 0; i < list.size(); i++) {
        	            // Create a line object, each line contains four elements.
        	            Object[] line = new Object[5];
        	            
        	            // Assign the value to the line object.
        	            line[0] = String.valueOf(list.get(i).getClientID());
        	            line[1] = String.valueOf(list.get(i).getJobID());
        	            line[2] = String.valueOf(list.get(i).getExecuteFileName());
        	            line[3] = String.valueOf(list.get(i).getStatus());
        	            // Create a button.
        	            JButton killButton = new JButton("Kill Job");
        	            line[4] = killButton;
        	            
        	            // Set the properties of the button.
        	            killButton.setName(String.valueOf(list.get(i).getJobID()));
        	            killButton.setText("Kill Job");
        	            
        	            // If this job hasn't finished,then disable the "Kill Job" button.
        	            if ("COMPLETED".equals(list.get(i).getStatus())) {
        	                killButton.setEnabled(false);
        	            }
        	            
        	            objects[acc+ i] = line;
        	            clientIDs.add(list.get(i).getClientID());
        	            jobIDs.add(list.get(i).getJobID());
        	        }
        	        
        	        acc += list.size();
        	        
        	        
        	    }
        	    jTable1.setModel(new javax.swing.table.DefaultTableModel(objects, new String[] { "CLIENT ID", "JOB ID", "JOB NAME", "STATE",
                "ACTION" }));
        	    jTable1.getColumn("ACTION").setCellRenderer(new MyRender(clientIDs, jobIDs, masterService));
            }
        });
	    GroupLayout layout = new GroupLayout(frame.getContentPane());
        frame.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 656, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(274, 274, 274)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

        frame.pack();
        JPanel pane = new JPanel(new BorderLayout());
        pane.add(frame.getContentPane());
        //frame2.setVisible(false);
        return pane;
	}
	/**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        //JFrame frame = new JFrame("DialogDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Server Info");
        //Create and set up the content pane.
        ServerInfoGUI newContentPane = new ServerInfoGUI(frame, frame2, masterService);
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public void run() {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}

class MyRender extends JButton implements TableCellRenderer {

	ArrayList<String> clientIDs; 
	ArrayList<Integer> jobIDs;
	MasterService masterService;
	public MyRender(ArrayList<String> clientIDs, ArrayList<Integer> jobIDs, MasterService masterService) {
		super();
		this.clientIDs = clientIDs;
		this.jobIDs = jobIDs;
		this.masterService = masterService;
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        JButton myButton = (JButton)value;
        this.setText(String.valueOf(myButton.getText()));
        this.setEnabled(myButton.isEnabled());
        if (isSelected) {
            //System.out.println("Row = " + row);
            //System.out.println("client=" + clientIDs.get(row) + " job=" + jobIDs.get(row));
        	masterService.killJobInWorkerJobList(clientIDs.get(row), jobIDs.get(row));
        }
        return this;
    }
}
